package com.zhang.gulimall.common.config;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Configuration
public class MyRabbitConfig {
//    @Resource
//    RabbitTemplate rabbitTemplate;
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制RabbitTemplate
     *  1.服务端收到消息回调
     *      1.rabbitmq.publisher-confirms=true
     *      2.设置ConfirmCallback
     *  2.消息未抵达队列回调
     *      1.rabbitmq.publisher-returns=true
     *      2.设置ReturnCallback
     *  3.消费者
     *      默认自动确认消息,但是服务器中途宕机会出现消息丢失问题
     *      1.rabbitmq.listener.simple.acknowledge-mode=manual 设置为手动
     *      手动模式只要不确认就会一直是unacked状态,服务器中途宕机会变为ready状态
     *      2.channel.basicAck()签收消息
     *        channel.basicNack()拒收消息
     *        消费者接受到消息后将消息从队列中移除
     *
     */

//    @PostConstruct
//    public void initRabbitTe(){
//        // Broker接受到消息回调
//        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
//            if (!ack){
//                System.out.println("correlationData==>["+correlationData+"]s==>["+cause+"]");
//            }
//        });
//        // 队列未接受到消息回调
//        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) ->
//                System.out.println("message==>["+message+"]replyCode==>["+replyCode+"]replyText==>["+replyText+"]exchange==>["+exchange+"]routingKey==>["+routingKey+"]"));
//    }
}
